﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using GeneralDFS.BusinessLogical.Config;
using GeneralDFS.BusinessLogical.Network;
using GeneralDFS.BusinessLogical.Nodes;
using GeneralDFS.Common;
using GeneralDFS.DataEntity.IO;

namespace GeneralDFS.BusinessLogical.NodeOperate
{
    public class SendBlock:INodeOperate
    {
        private DataNode dataNode;
        private string _fileName;
        private string _ip;
        private int _tcpPort;

        public void Operate()
        {
            Guid fileBlockName = Guid.Parse(_fileName);
            String filePath = dataNode.GetNodeConfig().DataNodeDirectory + @"\" + fileBlockName.ToString();
            if (System.IO.File.Exists(filePath) && System.IO.File.Exists(filePath + ".meta"))
            {
                var metaData =
                    SerializeHelper.GetModel(System.IO.File.OpenRead(filePath + ".meta")) as FileBlockMetaData;
                var socket = new AsyncDataNodeTcpClient((new ConfigCenter()).GetConfig(), _ip, _tcpPort);
                socket.Write(metaData, System.IO.File.OpenRead(filePath));
            }
        }
        //参数格式 param[0]为目标ip param[1]为目标端口 param[2]为文件名
        public void ProcessParam(string[] param)
        {
            if (param == null || param.Length == 0) return;
            if (param.Length == 3)
            {
                _ip = param[0];
                _tcpPort = int.Parse(param[1]);
                _fileName = param[2];
            }
        }

        public void ChangeDataNode(DataNode node)
        {
            dataNode = node;
        }
    }
}
